layui.define(['table', 'treeTable', 'form', 'laydate', 'tableSelect'], function (exports) {

    var $ = layui.$
        , form = layui.form
        , table = layui.table
        , setter = layui.setter
        , admin = layui.admin
        , treeTable = layui.treeTable
        , tableSelect = layui.tableSelect
        , layer = layui.layer
        , laydate = layui.laydate
        , admin = layui.admin
        
      //日期
        laydate.render({
          elem: '#startdate'
           ,type: 'date'
           ,trigger: 'click' 
        });
        laydate.render({
          elem: '#enddate'
      	  ,type: 'date'
      	  ,trigger: 'click' 
        });
    var goodscode = $('#goodscode', parent.document).val();
    if (goodscode == '') {
        layer.msg('请输入商品编码后在进行查询');
        return false;
    }
    var homeSelect = $('#goodscode', parent.document).val();
    var colsArr = [
                          {field: 'supplier', title: '供应商',width:100,align:'center'},
                          {field: 'suppliername', title: '供应商名称', align: 'center'}

                      ];
    //获取供应区域
    $.ajax({
		url: setter.host+'/dict_area/getSelectBody'
		,type:'post'
		,data:JSON.stringify({"search": {"flag":0},"limit":100,"asc":"asc","ascField":"id"})
    	,contentType:'application/json; charset=utf-8'
		,dataType:'json'
		,success: function(res){
			//请求成功后
			if(res.status == setter.response.statusCode.status_Success){
				$('#areaDiv').empty();
				layui.each(res.data,function(inxSub,valSub){
					  $('#areaDiv').append('<input type="checkbox" value="'+valSub.id+'" name="system['+valSub.id+']" title="'+valSub.name+'" >');
				  })
				  form.render('checkbox');
			}else{
				layer.msg(res.msg);
			}
		}
	});
//------------------------------------------
    //带查询条件
    var grouphaveCol = [];
    grouphaveCol.push({"colName": "goodscode", "colValue": goodscode});
    grouphaveCol.push({"colName": "flag", "colValue": 0});
//    grouphaveCol.push({"colName": "id", "colValue": id});

    //供应商
    table.render({
        elem: '#LAY-genius-table'
        , url: setter.host + '/goods_system_supplier/getGoodssupplier'
        , cols: [colsArr]
        , method: 'post'
        , contentType: 'application/json; charset=utf-8'
        , where: {'haveCol': grouphaveCol}
        , page: false
        , limit: 100
         ,height: 'full-80'
//        , width: w < 1500?850:950
        , done: function (res) {
            delete this.where;

        }
    });
    var actionType;//定义保存类型
  //监听行单击事件（双击事件为：rowDouble）
    table.on('row(LAY-genius-table)', function(obj){
      var data = obj.data;
      actionType = "edit";
      $('[lay-filter="form1"]')[0].reset();
	  $('input[type="checkbox"]').removeAttr('checked');
      var attributeArray = data.attribute.split(',');
      if(attributeArray[0] == '1'){
    	  data["attribute[jinhuo]"] = true;
//    	  $('input[name="attribute[jinhuo]"]').attr('checked','')
      }
      if(attributeArray[1] == '1'){
    	  data["attribute[tuihuo]"] = true;
//    	  $('input[name="attribute[tuihuo]"]').attr('checked','')
      }
      var systemArray = data.system.split(',');
      for (var i = 0; i < systemArray.length; i++) {
    	  data['system['+systemArray[i]+']'] = true;
//    	  $('input[name="system['+systemArray[i]+']"]').attr('checked','')
      }
//      console.log(data);
      form.val("form1", data);
//      $('#supplier').val(data.supplier);
//      $('#suppliername').val(data.suppliername);
//      $('#inprice').val(data.inprice);
//      $('#intaxrate').val(data.intaxrate);
//      $('#boxnumber').val(data.boxnumber);
//      $('#startdate').val(data.startdate);
//      $('#enddate').val(data.enddate);
//      $('#remark').val(data.remark);
      
      
      form.render('checkbox');
      
//      layer.alert(JSON.stringify(data), {
//        title: '当前行数据：'
//      });
//      
//      //标注选中样式
//      obj.tr.addClass('layui-table-click').siblings().removeClass('layui-table-click');
    });

//	-------------------------------------------------------------------------------------------
    var goodsColsArr = [
                        {type: 'radio'},
                        {field: 'suppliercode', title: '供应商编码', sort: false},
                        {field: 'suppliername', title: '供应商名称', sort: false},
                        ];
    var goodsTableHead = '';
    layui.each(goodsColsArr, function (inx, val) {
    	goodsTableHead += val.hasOwnProperty('field') ? val.field + ',' : ',';
    })
    goodsTableHead = goodsTableHead.substring(goodsTableHead.indexOf(',') + 1, goodsTableHead.length - 1);
    $(document).on('click', '#supplier', function(data) {
    	if(actionType == 'add'){
    		//带查询条件
            var haveCol = [];
    		haveCol.push({"colName":"flag","colValue":0});
            tableSelect.render({
                elem: '#supplier',
                checkedKey: 'suppliercode',
                height: '350',
                width: '450',
                searchType: 'more',
                searchList: [
                    {searchKey: 'suppliercode', searchPlaceholder: '供应商编码'},
                    {searchKey: 'suppliername', searchPlaceholder: '供应商名称'}
                ],
                table: {
                    url: layui.setter.host + '/supplier_info/getSelectBody'
                    , method: 'post'
                    , where: {'headField': goodsTableHead, 'haveCol': haveCol}
                    , contentType: 'application/json; charset=utf-8'
                    , page: true
                    , groups: 2
                    , limit: 20
                    , limits: [20, 30, 50]
                    , text: {
                        none: '暂无相关数据'
                    }
                    , cols: [goodsColsArr]
                },
                done: function (elem, data) {
                    $('#supplier').val(data.data[0].suppliercode);
                    $('#suppliername').val(data.data[0].suppliername);
                }
            });
    	}
        

    });

//	-------------------------------------------------------------------------------------------	
    
    var active = {
		batchdel: function(){
			var delData =[];
			var supplier = $('#supplier').val();
			var delOne = {};
			delOne.supplier = supplier;
			delOne.goodscode = goodscode;
			delData.push(delOne)
			console.log(delData);
			layer.prompt({
				formType: 1
				,title: '敏感操作，请验证口令'
			}, function(value, index){
				var command = layui.sessionData('layuiSession').command;
				if(value == command){
					layer.close(index);
					layer.confirm('确定删除吗？', function(index_confirm) {
						layer.close(index_confirm);
						var delIds ={'delData':delData};
						layui.admin.req({
			        	    url: setter.host+'/goods_system_supplier/batchdel'
			        	    ,type:'post'
			        	    ,dataType:'json'
			        	    ,contentType: "application/json; charset=utf-8"
			        	    ,data:JSON.stringify(delIds) 
			        	    ,done: function(res){
			        	    	//请求成功后
			        	    	if(res.status == setter.response.statusCode.status_Success){
			        	    		actionType = "add";
			        	    		$('[lay-filter="form1"]')[0].reset();
			        	    		$('input[type="checkbox"]').removeAttr('checked');
			        				form.render('checkbox');
			        				table.reload('LAY-genius-table',{
										where: { //请求参数（注意：这里面的参数可任意定义，并非下面固定的格式）
											'haveCol': grouphaveCol
										}
										,done:function () {		
											delete this.where; 
										}
									}); 
									layer.msg(res.msg);
								}else{
									layer.msg(res.msg);
								}
			        	    }
						});
					});
				}else{
					layer.msg('口令错误');
				}
			});
		}
    		//新增的事件方法
    	,add: function () {
    		actionType = 'add';
    		$('[lay-filter="form1"]')[0].reset();
    		$('input[type="checkbox"]').removeAttr('checked');
			form.render('checkbox');
        },
        save: function () {
        	form.on('submit(save)', function(data){
				var field = data.field;
				var jinhuo = 1,tuihuo = 1;
				if(data.field["attribute[tuihuo]"] == undefined){
					tuihuo = 0;
				}
				if(data.field["attribute[jinhuo]"] == undefined){
					jinhuo = 0;
				}
				field.attribute = jinhuo+","+tuihuo;
				var fieldArray = [];
				$('input[type="checkbox"][name^="system"]:checked').each(function(i,obj){
					var oneData = {};
					oneData.goodscode= goodscode;
					oneData.attribute= field.attribute;
					oneData.boxnumber= field.boxnumber;
					oneData.enddate= field.enddate;
					oneData.inprice= field.inprice;
					oneData.intaxrate= field.intaxrate;
					oneData.remark= field.remark;
					oneData.startdate= field.startdate;
					oneData.supplier= field.supplier;
					oneData.suppliername= field.suppliername;
					oneData.flag= 0;
					oneData.system= $(obj).val();
					fieldArray.push(oneData);
				});
				
				var modifyUrL = layui.setter.host+'/goods_system_supplier/editall';
//				if(actionType == 'edit')
//					modifyUrL = layui.setter.host+'/goods_system_supplier/edit';
				layui.admin.req({
					url: modifyUrL
					,type:'post'
					,dataType:'json'
					,contentType: "application/json; charset=utf-8"
					,data:JSON.stringify(fieldArray) 
					,done: function(res){
						//请求成功后
						if(res.status == setter.response.statusCode.status_Success){
							table.reload('LAY-genius-table',{
								where: { //请求参数（注意：这里面的参数可任意定义，并非下面固定的格式）
									'haveCol': grouphaveCol
								}
								,done:function () {		
									delete this.where; 
								}
							}); 
							actionType = "edit";
						}
						layer.msg(res.msg);
					}
				});
			});
			$('[lay-filter="save"]').trigger('click');
        }
    }


    $('.layui-btn').on('click', function () {
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });


});
//---------------------------------------------------------------------------
//roleTable = table.render({
//elem: '#LAY-role-list1'
//,url:'/unite_platform/goods_class/getclasslabel'
//,cols: [[
//{type:'checkbox'}
//,{field:'id', width:80, title: 'ID', sort: true}
//,{field:'name', width:80, title: '用户名'}
//]]
//,page: true
//});



